# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import logging
import re

from google.appengine.api import users
from google.appengine.ext import db

import django
from django import http
from django import shortcuts

from django.http import HttpResponse
from django.http import HttpResponseRedirect

from django.template import loader, Context
from django.template import add_to_builtins

from django.utils import simplejson

DEBUG = True


# DO NOT EDIT BELOW HERE UNLESS YOU KNOW WHAT YER UP TO
def login_required(func):
  def _wrapper(request, *args, **kw):
    user = users.get_current_user()
    if user:
      return func(request, *args, **kw)
    else:
      return HttpResponseRedirect(users.create_login_url(request.get_full_path()))

  return _wrapper


def respond(request, template=None, params=None):
  """Helper to render a response, passing standard stuff to the response.

  Args:
    request: The request object.
    template: The template name; '.html' is appended automatically.
    params: A dict giving the template parameters; modified in-place.

  Returns:
    Whatever render_to_response(template, params) returns.

  Raises:
    Whatever render_to_response(template, params) raises.
  """
  logging.info('views.respond %s, %s' %
               (template, params))

  if params is None:
    params = {}

  # Sets a BUILD_VERSION variable for the templates to use.
  # Default to production and then set to development if we're local.
  BUILD = 'production'
  if 'Dev' in os.getenv('SERVER_SOFTWARE'):
    BUILD = 'development'
  params['BUILD'] = BUILD

  params['SERVER_NAME'] = request.META['SERVER_NAME']
  params['SERVER_PORT'] = request.META['SERVER_PORT']

  # Sets the CURRENT_VERSION_ID for file fingerprinting.
  params['CURRENT_VERSION_ID'] = os.getenv('CURRENT_VERSION_ID')


  # HTML is our default output.
  output = 'html'

  # We can override that in request or params.
  if request.REQUEST.has_key('output'):
    output = request.REQUEST['output']
  elif params.has_key('output'):
    output = params['output']
  params['output'] = output

  # HTML is our default output.
  if output == 'html':
    base_template = 'base.html'
  else:
    base_template = 'base_%s.html' % output
  params['base_template'] = base_template
  logging.info('base_template: %s' % base_template)


  # Template
  if template and not template.endswith('.html'):
    template += '.html'
  logging.info('template: %s' % template)

  # JSON
  if output == 'json':
    logging.info('output is json, dumping params: %s' % params)
    # User can't be serialized.
    params['user'] = None
    return HttpResponse(simplejson.dumps(params))

  # Otherwise, render the template normally
  return shortcuts.render_to_response(template, params)
